//
//  CLReadTextParser.m
//  CLBrowser
//
//  Created by 梁慧聪 on 2022/8/13.
//

#import "CLReadTextParser.h"

@implementation CLReadTextParser

/// 异步解析本地链接
///
/// - Parameters:
///   - url: 本地文件地址
///   - completion: 解析完成
+ (void)parser:(NSURL *)url completion:(CLParserCompletion)completion {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        
        CLReadModel *readModel = [self parser:url];
        
        dispatch_main_safe_async(^{
            CLSafeExecuteBlock(completion,readModel);
        });
    });
}
    
/// 解析本地链接
///
/// - Parameter url: 本地文件地址
/// - Returns: 阅读对象
+ (CLReadModel *)parser:(NSURL *)url {
        
    // 链接不为空且是本地文件路径
    if (url == nil || url.absoluteString.isEmpty || !url.isFileURL) { return nil; }
        
    // 获取文件后缀名作为 bookName
    NSString *bookName = [[url.absoluteString stringByRemovingPercentEncoding].lastPathComponent stringByDeletingPathExtension];
    bookName = StrNilHolder(bookName, @"");
        
        // bookName 作为 bookID
    NSString *bookID = bookName;
        
        // bookID 为空
    if (NULLString(bookID)) { return nil; }
    
    if (![CLReadModel isExist:bookID]) {
        
        // 解析数据
        NSString *content = [CLReadParser encode:url];
        
        // 解析失败
        if (NULLString(content)) { return nil; }
        
        // 解析内容并获得章节列表
        NSArray <CLReadChapterListModel *>*chapterListModels = [self parser: bookID content: content];
        
        // 解析内容失败
        if (chapterListModels == nil || chapterListModels.isEmpty) { return nil; }
        
        // 阅读模型
        CLReadModel *readModel = [CLReadModel model: bookID];
        
        // 书籍类型
        readModel.bookSourceType = BookSourceTypeLocal;
        
        // 小说名称
        readModel.title = bookName;
        
        // 记录章节列表
        readModel.chapterListModels = chapterListModels;
        
        // 设置第一个章节为阅读记录
        [readModel.recordModel modify:readModel.chapterListModels.firstObject.chapterid toPage:0 isSave:YES];
        
        // 保存
        [readModel save];
        
        return readModel;
    } else {
        return [CLReadModel model:bookID];
    }
}

/// 解析整本小说
///
/// - Parameters:
///   - bookID: 小说ID
///   - content: 小说内容
/// - Returns: 章节列表
+ (NSArray <CLReadChapterListModel *>*)parser:(NSString *)bookID content:(NSString *)content {
    
    // 章节列表
    NSMutableArray <CLReadChapterListModel *>*chapterListModels = [NSMutableArray array];

    // 正则
    NSString *parten = @"第[0-9一二三四五六七八九十百千]*[章回].*";

    // 排版
    content = [CLReadParser contentTypesetting:content];

    // 正则匹配结果
    NSArray <NSTextCheckingResult *>*results = @[];

    // 开始匹配
    results = [content matchesByPattern:parten];

    // 解析匹配结果
    if (results && !results.isEmpty) {

        // 章节数量
        NSInteger count = results.count;

        // 记录最后一个Range
        NSRange lastRange = NSMakeRange(0, 0);

        // 记录最后一个章节对象C
        CLReadChapterModel *lastChapterModel = nil;

        // 有前言
        BOOL isHavePreface = YES;

        // 便利
        for (int i = 0; i < count; i++) {
           
            NSRange range = NSMakeRange(0, 0);
            NSInteger location = 0;
            if (i < count) {
                
                range = results[i].range;
                
                location = range.location;
            }
            
            // 章节内容
            CLReadChapterModel *chapterModel = [[CLReadChapterModel alloc]init];
            chapterModel.isTemp = YES;
            // 书ID
            chapterModel.bookid = bookID;
            
            // 章节ID
            chapterModel.chapterid = @(i + (isHavePreface?1:0)).stringValue;
            
            // 章节数量分析:
            // count + 1  = 匹配到的章节数量 + 最后一个章节
            // 1 + count + 1  = 第一章前面的前言内容 + 匹配到的章节数量 + 最后一个章节
            NSLog(@"章节总数: %@  当前正在解析: %@ - %@",@(count + 1),@(i + 1),chapterModel.chapterid);
            
            // 优先级
            chapterModel.priority = i - (isHavePreface?0:1);
            
            if (i == 0) { // 前言
                
                // 章节名
                chapterModel.name = @"开始";
                
                // 内容
                chapterModel.content = [content substringWithRange:(NSMakeRange(0, location))];
                
                // 记录
                lastRange = range;
                
                // 没有内容则不需要添加列表
                if (NULLString(chapterModel.content)) {
                    
                    isHavePreface = NO;
                    
                    continue;
                }
                
            }else if (i == count) { // 结尾
                
                // 章节名
                chapterModel.name = [content substringWithRange:lastRange];
                
                // 内容(不包含章节名)
                chapterModel.content = [content substringWithRange:NSMakeRange(lastRange.location + lastRange.length, content.length - lastRange.location - lastRange.length)];
                
            }else { // 中间章节
                
                // 章节名
                chapterModel.name = [content substringWithRange:lastRange];
                
                // 内容(不包含章节名)
                chapterModel.content = [content substringWithRange:NSMakeRange(lastRange.location + lastRange.length, location - lastRange.location - lastRange.length)];
            }
            // 章节开头双空格 + 章节纯内容
            chapterModel.content = [NSString stringWithFormat:@"%@%@",CL_READ_PH_SPACE, [chapterModel.content removeSEHeadAndTail]];
            
            // 设置上一个章节ID
            chapterModel.previousChapterID = lastChapterModel.chapterid ?: CL_READ_NO_MORE_CHAPTER;
            
            // 设置下一个章节ID
            if (i == (count - 1)) { // 最后一个章节了
                chapterModel.nextChapterID = CL_READ_NO_MORE_CHAPTER;
            }else{
                lastChapterModel.nextChapterID = chapterModel.chapterid;
            }
            
            // 保存
            [chapterModel save];
            [lastChapterModel save];
            
            // 记录
            lastRange = range;
            lastChapterModel = chapterModel;
            
            // 通过章节内容生成章节列表
            [chapterListModels addObject:[self getChapterListModel:chapterModel]];
        }
    } else {
        // 章节内容
        CLReadChapterModel *chapterModel = [[CLReadChapterModel alloc]init];
        chapterModel.isTemp = YES;
        // 书ID
        chapterModel.bookid = bookID;
        
        // 章节ID
        chapterModel.chapterid = @"1";
        
        // 章节名
        chapterModel.name = @"开始";
        
        // 优先级
        chapterModel.priority = 0;
        
        // 内容
        chapterModel.content = [NSString stringWithFormat:@"%@%@",CL_READ_PH_SPACE, [chapterModel.content removeSEHeadAndTail]];
        
        // 保存
        [chapterModel save];
        
        // 添加章节列表模型
        [chapterListModels addObject:[self getChapterListModel:chapterModel]];
    }
    NSLog(@"解析内容：%ld",chapterListModels.lastObject.content.length);
    // 返回
    return chapterListModels;
}

/// 获取章节列表对象
///
/// - Parameter chapterModel: 章节内容对象
/// - Returns: 章节列表对象
+ (CLReadChapterListModel *)getChapterListModel:(CLReadChapterModel*)chapterModel {
    
    CLReadChapterListModel *chapterListModel = [[CLReadChapterListModel alloc]init];
    
    chapterListModel.bookid = chapterModel.bookid;
    
    chapterListModel.chapterid = chapterModel.chapterid;
    
    chapterListModel.name = chapterModel.name;
    
    chapterListModel.content = chapterModel.content;
    return chapterListModel;
}
@end
